package cn.com.callback

import groovy.json.*;
import java.util.Map;

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import java.text.ParseException
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import cn.com.elite.Util;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;


/**
 *
 * @Title: Bp_Api_Get_CGCaseflow
 * @Description: 宝安排水 同步案件流程信息
 * @author: chieh
 * @date 2020-08-15 12:30:00
 *
 */

public class Bp_Api_Get_CGCaseflow implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(Bp_Api_Get_CGCaseflow.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {
		def szhtokresult =eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SZHTOK' and MODIFIEDDATE>dateadd(minute,-1,GETDATE())", "dataSource");
		def szhtok;
		if(szhtokresult.size() > 0) {
			szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
			log.debug("szhtok:	"+szhtok);
		}
		if(szhtok==null){
			szhtok=getCaseTasks(eliteBean);
		}
		log.debug("szhtok1:	"+szhtok);

		getCaseList(eliteBean,szhtok);
		return "同步成功";
	}

	// 同步案件待办信息
	public void getCaseList(EliteBean eliteBean,String szhtok){

		String logPrefix = "同步案件流程信息-";
		log.debug(logPrefix + "开始...");
		long rstartTime,rendTime;
		def actinstid,RELATION_ID;
		String json,errorMsg;
		rstartTime = System.currentTimeMillis();
		log.debug(logPrefix + "开始处理时间:" + rstartTime);

		try {
			String URL = getProperty.get("SZCG.URL")+"/swEvent/GetActivityInstanceList?access_token="+szhtok;
			//获取未结案，来件时间在七天内以内的城管案件 流程ID
			//def	samp = "select tc.wfinstid as actinstid from TABCCONSULTWORKORDER tc left JOIN  objective o on tc.RELATION_ID=o.objective_guid where tc.business_source='9999B1' and tc.actinstid is not null and o.objectivestatus='OPEN' and tc.come_time>DATEADD(day, -7, GETDATE())";
			def	samp = "select tc.RELATION_ID as RELATION_ID,tc.wfinstid as actinstid from TABCCONSULTWORKORDER tc left JOIN  objective o on tc.RELATION_ID=o.objective_guid where tc.business_source='9999B1' and tc.actinstid is not null and tc.come_time>DATEADD(day, -15, GETDATE()) order by tc.come_time desc";
			
			List allCGGDList = eliteBean.chaxun_sql(samp, "dataSource");
			log.debug("查询一个月内的数字化城管案件流程状态数据SQL:" + samp);

			def ListNum = allCGGDList.size();
			if(ListNum > 0){
				for(int i = 0; i<ListNum; i++) {
					Map CGGDMap = allCGGDList.get(i);
					RELATION_ID = CGGDMap.get("RELATION_ID");
					actinstid = CGGDMap.get("actinstid");
					json ="{wfInstID:\""+actinstid+"\"}";

					// 设置头文件
					Map<String, String> headMap = new HashMap<String, String>();
					headMap.put("Content-Type", "application/json");
					log.debug(logPrefix + "调用地址URL：" + URL);
					log.debug(logPrefix + "调用发送报文信息：" + json);
					String reJson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);


					log.debug(logPrefix + "调用返回信息：" + reJson.toString());
					JSONObject inObject = new JSONObject(reJson);
					String statusCode = KHUtil.GetJV(inObject, "statusCode");
					errorMsg = KHUtil.GetJV(inObject, "errorMsg");
					String result = KHUtil.GetJV(inObject, "result");

					if(statusCode.equals("0")) {
						JSONArray arrJsonArray = new JSONArray(result);
						int arrInt = arrJsonArray.length();
						log.debug("接入List数量:" + arrInt);

						String  uuid36 = UUID.randomUUID().toString();
						log.debug("uuid36:" + arrInt);
						
						//查询更新案件流程
							String[] GDSQL = new String[3];
							GDSQL[0] = "delete from SZWG_DE_Case_Tasks_his where createdate<=dateadd(minute,-30,GETDATE()) and objective_guid = '"+RELATION_ID+"'";							
							GDSQL[1] = "Insert into SZWG_DE_Case_Tasks_his select '"+uuid36+"',* from SZWG_DE_Case_Tasks where objective_guid = '"+RELATION_ID+"'";
							GDSQL[2] = "delete from SZWG_DE_Case_Tasks where objective_guid = '"+RELATION_ID+"'";
							log.debug(logPrefix + "归档结果SQL:" + GDSQL.toString());
							def GDresult = eliteBean.updateBatch(GDSQL, "dataSource");
							log.debug(logPrefix + "查询现有流程任务编号不存在新建结果SQL结果:" + GDresult.toString());
						
						for (int j = 0; j < arrInt; j++) {
							JSONObject arrCustJson = arrJsonArray.getJSONObject(j);
							//获取案件流程信息
							String actID = GetJV(arrCustJson, "actID");//流程环节ID
							String name = GetJV(arrCustJson, "name");//环节名称
							String receiveObjectName = GetJV(arrCustJson, "receiveObjectName");//环节接收对象
							String operatorName = GetJV(arrCustJson, "operatorName");//办理人
							String usedLimit = GetJV(arrCustJson, "usedLimit");//环节用时 单位(秒)
							String content = GetJV(arrCustJson, "content");//内容
							String indate = GetJV(arrCustJson, "indate");//来件时间
							String ActivityIdentifier = GetJV(arrCustJson, "ActivityIdentifier");//案件环节GUID
							String limit = GetJV(arrCustJson, "limit");//办理时限: 单位（秒）  0：不设时限
							String finishedDate = GetJV(arrCustJson, "finishedDate");//办结时间

							//查询更新案件流程
							String[] batchSQL = new String[1];
							batchSQL[0] = "INSERT INTO SZWG_DE_Case_Tasks (actID, name, receiveObjectName, operatorName, usedLimit, content, indate, ActivityIdentifier, limit, finishedDate,createdate,objective_guid) VALUES ('"+actID+"', '"+name+"', '"+receiveObjectName+"', '"+operatorName+"', '"+usedLimit+"', '"+content+"', '"+indate+"', '"+ActivityIdentifier+"', '"+limit+"', '"+finishedDate+"',GETDATE(), '"+RELATION_ID+"')";
							log.debug(logPrefix + "查询现有流程任务编号不存在新建结果SQL:" + batchSQL.toString());
							def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
							log.debug(logPrefix + "查询现有流程任务编号不存在新建结果SQL结果:" + dataresult.toString());
						}
						//生成处理完成时间
						rendTime = System.currentTimeMillis();
					}
				}
			}

			// 包装拼接返回JSONObject
			log.debug(logPrefix + "流程同步调用问题处理时长(毫秒):" + (rendTime - rstartTime)+"，接口返回："+errorMsg);

		} catch (JSONException e) {
			rendTime = System.currentTimeMillis();
			log.error(logPrefix + "处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (rendTime - rstartTime));
		}

	}

	// 获取token
	public static String getCaseTasks(EliteBean eliteBean) {
		log.debug("-------------------------start Bp_Get_CGToKen 开始-----------------");
		def sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/Bp_Get_CGToKen";
		String reJson = Util.doHttpGet(sysurl, "UTF-8", 10000, 0);
		JSONObject inObject = new JSONObject(reJson);
		log.debug("ToKen报文："+reJson);

		String resultcode = KHUtil.GetJV(inObject, "resultcode");
		String data = KHUtil.GetJV(inObject, "data");
		log.debug("resultcode	"+resultcode);
		log.debug("data	"+data);

		return data;
	}
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}

}